package com.zhang.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class MyBatisUtils {
	private static ThreadLocal<SqlSession> tl = new ThreadLocal<>();
	private static SqlSessionFactory factory = null;
	static {
		try {
			InputStream stream = Resources.getResourceAsStream("mybatis-config.xml");
			factory = new SqlSessionFactoryBuilder().build(stream);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static SqlSession getSqlSession() {	
		if(tl.get() == null) {
			SqlSession sqlSession = factory.openSession();
			tl.set(sqlSession);
		}
		return tl.get();
	}
	
	public static void closeSqlSession(SqlSession sqlSession) {
		if(sqlSession != null) {
			sqlSession.close();
			tl.remove();
		}
	}
}
